const { Op, fn, col } = require("sequelize");
var { Article, User, Label, Comment } = require("./../models.js");
const fs = require('fs')
const path = require('path')
const moment = require("moment")
module.exports.createArticle = async (req, res) => {

	const { title, content, cover_url, label, file_url } = req.body;
	console.log(title, content, cover_url, label);
	const article = await Article.create({ userId: req.query.user.id, title, content, cover_url, file_url })
	label.forEach(async label => {
		await article.createLabel({
			label
		})
	})
	res.sendResult(article, 0, '创建文章成功')
	try {
	} catch (error) {
		res.sendResult(error, 1, '创建文章失败')

	}
}
module.exports.editArticle = async (req, res) => {
	const { id, content, title, cover_url, label } = req.body;
	const article = await Article.update({
		content: content,
		title: title,
		cover_url: cover_url
	}, {
		where: {
			id: id
		}
	})
	await Label.destroy({ where: { articleId: id } })
	label.forEach(async label => {
		await Label.create({
			label,
			articleId: id
		})
	})

	try {
		res.sendResult(article, 0, '修改文章成功')
	} catch (error) {
		res.sendResult(error, 1, '修改文章失败')

	}
}
module.exports.findArticle = async (req, res) => {
	const { userId, title, page = { pageSize: 10, pageNumber: 1 }, filters, label, pageSize } = req.body;
	try {

		let params = {
			title: {
				[Op.like]: '%' + (title ? title : '') + '%'
			},
		}
		if (userId) {
			params[userId] = userId
		}
		let labelFind = { model: Label }
		if (label && (label !== '')) {
			labelFind['where'] = { label }
		}
		let articles = await Article.findAndCountAll({
			include: [
				labelFind,
				{
					model: User, attributes: {
						exclude: ['password']
					}
				}],
			distinct: true,
			where: params,
			limit: pageSize ? pageSize : page.pageSize,
			offset: pageSize ? (pageSize * (page - 1)) : (page.pageSize * (page.pageNumber - 1)),
		})
		res.sendResult(articles, 0, '文章获取成功')
	} catch (error) {
		res.sendResult(error, 1, '文章获取失败')

	}
}

module.exports.findArticleById = async (req, res) => {
	const { articleId } = req.query;
	try {
		const article = await Article.findAll({
			include: [Label, {
				model: User, attributes: {
					exclude: ['password']
				}
			}],
			where: {
				id: articleId
			},
		})
		const articleAll = await Article.findAll({
			attributes: ['id', 'title']
		})

		res.sendResult({ article, articleAll }, 0, '文章获取成功')
	} catch (error) {
		res.sendResult(error, 0, '文章获取失败')
	}
}


module.exports.deleteArticle = async (req, res) => {
	const { articleId } = req.query;
	const labels = await Label.destroy({ where: { articleId } })
	const { cover_url, content, file_url } = await Article.findByPk(articleId);
	let imgList = findContentImg(content);
	if (!cover_url.includes('article_background')) {
		imgList.push(cover_url)
	}
	if (file_url) {
		imgList.push('file_url', file_url)
	}
	console.log(file_url);

	imgList.forEach(url => {
		fs.unlink(path.resolve(url), err => {
			console.log(err);
		})
	})
	const article = await Article.destroy({ where: { id: articleId } })

	res.sendResult(null, 0, '删除文章成功')
	try {
	}
	catch (error) {
		res.sendResult(error, 1, '删除文章失败')

	}
}

function findContentImg(content) {
	let imgList = [];
	let regExp = new RegExp(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi)
	let item = regExp.exec(content)
	while (item) {
		imgList.push(item[1]);
		item = regExp.exec(content)
	}
	return imgList
}

module.exports.findAllLabel = async (req, res) => {
	try {
		const labels = await Label.findAll({
			attributes: [
				'label',
				[fn('COUNT', col('label')), 'count']
			],
			group: 'label'
		});
		return res.sendResult(labels, 0, '根据标签查找成功')
		// const labels = await Label.findAll({})

	} catch (error) {
		return res.sendResult(error, 1, '获取标签失败')
	}
}
module.exports.getArticleOption = async (req, res) => {
	try {
		const articleAll = await Article.findAll({
			attributes: ['id', 'title']
		})
		return res.sendResult(articleAll, 0, '根据标签查找成功')
	} catch (error) {
		return res.sendResult(error, 1, '获取标签失败')
	}
}
